<template>
  <div class="editPersonal">
    <myheader title="编辑资料">
      <!-- 插槽使用 带上slot name标识 -->
      <!-- $router.back()  回退到前一个页面 -->
      <van-icon
        name="arrow-left"
        size="18"
        slot="left"
        @click="$router.back()"
      />
      <van-icon
        name="wap-home-o"
        size="24"
        color="#f00"
        slot="right"
        @click="$router.push({ path: '/index' })"
      />
    </myheader>
    <div class="userImg">
      <img :src="currentuser.head_img" alt="" />
      <van-uploader :after-read="afterRead" />
    </div>
    <mycell
      title="昵称"
      :desc="currentuser.nickname"
      @click="nickshow = !nickshow"
    >
    </mycell>
    <!-- 弹框 -->
    <!--  van-dialog的v-model的作用是控制对话框显示和隐藏-->
    <van-dialog
      v-model="nickshow"
      title="修改昵称"
      show-cancel-button
      @confirm="editNickname"
      @open="handlerOpen"
    >
      <!-- van-field的v-model是实现双向绑定 -->
      <van-field v-model="nickname" label="昵称" placeholder="请输入新昵称" />
    </van-dialog>

    <mycell
      title="密码"
      :desc="currentuser.password"
      type="pass"
      @click="passshow = !passshow"
    >
    </mycell>

    <van-dialog
      v-model="passshow"
      title="修改密码"
      show-cancel-button
      @confirm="editPass"
      :before-close="beforeClose"
    >
      <!-- van-field的v-model是实现双向绑定 -->
      <van-field
        v-model="originpass"
        label="原始密码"
        placeholder="请输入原始密码"
        required
      />
      <van-field
        v-model="newpass"
        label="新密码"
        placeholder="请输入新密码"
        required
      />
    </van-dialog>

    <mycell
      title="性别"
      :desc="currentuser.gender == 0 ? '女' : '男'"
      @click="gendershow = !gendershow"
    >
    </mycell>
    <van-dialog
      v-model="gendershow"
      title="修改性别"
      show-cancel-button
      @confirm="editGender"
    >
      <van-picker
        :columns="['女', '男']"
        @change="onChange"
        :default-index="currentuser.gender"
      />
    </van-dialog>
  </div>
</template>

<script>
import myheader from "../components/myheader.vue";
import mycell from "../components/mycell.vue";
import axios from "@/utils/myaxios";
import { getUserInfo, edit_profile } from "@/api/user.js";
import { fileUpload } from "@/api/fileUpload.js";

export default {
  data() {
    return {
      currentuser: {},
      nickshow: false,
      nickname: "", //弹框昵称
      passshow: false,
      originpass: "",
      newpass: "",
      gendershow: false,
      newgender: "",
    };
  },
  components: {
    myheader,
    mycell,
  },
  methods: {
    async afterRead(myfile) {
      // 此时可以自行将文件上传至服务器
      // 触发afterRead的时候，仅说明这个组件已经获取到用户所选择的文件对象
      // console.log(myfile);
      let formdata = new FormData();
      formdata.append("file", myfile.file);
      let res = await fileUpload(formdata);
      // console.log(res);
      // 重新设置userinfo的head_img的值，以实现预览更新
      this.currentuser.head_img = axios.defaults.baseURL + res.data.data.url;
      let result = await edit_profile(this.currentuser.id, {
        head_img: res.data.data.url,
      });
      // console.log(result);  //修改成功
    },
    // 修改昵称
    async editNickname() {
      if (this.nickname.trim().length == 0) {
        this.$toast.fail("请输入昵称");
        return;
      }
      let resName = await edit_profile(this.currentuser.id, {
        nickname: this.nickname,
      });
      if (resName.data.message == "修改成功") {
        this.$toast.success("修改成功");
        this.currentuser.nickname = this.nickname;
      }
    },
    handlerOpen() {
      this.nickname = this.currentuser.nickname;
    },
    // 修改密码
    async editPass() {
      // 判定用户原始密码是否正确;
      // 正确情况
      if (this.originpass.trim() == "" || this.newpass.trim() == "") {
        this.$toast.fail("请输入非空密码");
        return;
      }
      if (this.originpass == this.currentuser.password) {
        // console.log(this.currentuser.password);
        // console.log(this.newpass);
        let resPass = await edit_profile(this.currentuser.id, {
          password: this.newpass,
        });
        if (resPass.data.message == "修改成功") {
          this.$toast.success("修改成功");
          // 这里的重置并不是为了页面的展示效果，目的是为了用户在重置密码的时候能够正确的进行原始密码的匹配
          this.currentuser.password = this.newpass;
          // this.originpass = this.newpass = "";
        }
      } else {
        this.$toast.fail("原始密码输入不正确");
      }
    },
    beforeClose(action, done) {
      // 只有用户单击了确认，且原始密码输入不正确的时候才需要阻止弹窗的关闭
      if (action == "confirm" && this.originpass != this.currentuser.password) {
        this.$toast.fail("原始密码输入不正确");
        done(false);
      } else if (
        action == "confirm" &&
        (this.originpass.trim() == this.newpass.trim()) == ""
      ) {
        this.$toast.fail("请输入非空密码");
        done(false);
      } else {
        done();
        setTimeout(() => {
          this.originpass = this.newpass = "";
        }, 200);
      }
    },

    onChange(picker, value, index) {
      // console.log(picker, value, index);
      // picker:当前组件实例  value:当前组件所展示的值  index:索引
      // 注意，索引就和后台所需要的0，1对应
      this.newgender = index;
    },
    // 修改性别、
    async editGender() {
      let resPass = await edit_profile(this.currentuser.id, {
        gender: this.newgender,
      });
      if (resPass.data.message == "修改成功") {
        this.$toast.success("修改成功");
        this.currentuser.gender = this.newgender;
      }
    },
  },
  async mounted() {
    // console.log(this.$route);
    let id = this.$route.params.id;
    // console.log(id);
    let res = await getUserInfo(id);
    // console.log(res);
    // 细节注意：图片不一定有
    // 新用户第一次进入页面，图片是不存在的。如果存在也要注意只有目录+文件名
    if (res.data.message === "获取成功") {
      this.currentuser = res.data.data;
      this.nickname = this.currentuser.nickname;
      if (this.currentuser.head_img) {
        this.currentuser.head_img =
          axios.defaults.baseURL + this.currentuser.head_img;
      } else {
        this.currentuser.head_img =
          axios.defaults.baseURL + "/uploads/image/default.png";
      }
    } else {
      this.$router.push({ name: "Login" });
    }
  },
};
</script>

<style lang="less" scoped>
.editPersonal {
  .userImg {
    position: relative;
    width: 100%;
    height: 150px;
    display: flex;
    justify-content: center;
    align-items: center;
    > img {
      width: 90 * 100vw/360;
      height: 90 * 100vw/360;
    }
    /deep/.van-uploader__upload {
      width: 90 * 100vw/360;
      height: 90 * 100vw/360;
    }
    // 定位
    /deep/.van-uploader {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      opacity: 0;
    }
  }
}
// 重置文件上传组件的样式-使用深度选择器，能够在父组件中影响子组件的样式
// 大小
</style>